package com.hdl.school.schoolcontroller;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.hdl.school.adapter.SerialMessageAdapter;
import com.hdl.school.bean.SerialMessage;
import com.hdl.school.utils.Constants;
import com.hdl.school.utils.TCWManager;
import com.hdl.school.utils.USBSerialManager;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class USBSerialLogActivity extends CardSlotActivity {
    private SerialMessageAdapter serialMessageAdapter;

    @ViewInject(R.id.serial_message_list)
    private RecyclerView serialMessageListView;

    @ViewInject(R.id.portSpinner)
    private Spinner portSpinner;

    @ViewInject(R.id.messageSend)
    private EditText messageSend;


    private String cPort="USB1";
    private TCWManager tcwManager;

    private String[] ioTags=new String[]{null,null,null};

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
//                    String txt=readTxtFile("sys/class/gpio_sw/PB16/data");
//                    if("1".equals(txt)){
//                        tcwManager.execSuCmd("echo 0 > sys/class/gpio_sw/PB15/data");
//                        tcwManager.execSuCmd("echo 0 > sys/class/gpio_sw/PB16/data");
//                        tcwManager.execSuCmd("echo 0 > sys/class/gpio_sw/PB17/data");
//                        tcwManager.execSuCmd("echo 0 > sys/class/gpio_sw/PH0/data");
//                      //  tcwManager.execSuCmd("echo 0 > sys/class/gpio_sw/PH1/data");
//                        serialMessageAdapter.addItem(new SerialMessage("GPIO3","IO断电","OUT"));
//                        serialMessageAdapter.addItem(new SerialMessage("GPIO4","IO断电","OUT"));
//                        serialMessageAdapter.addItem(new SerialMessage("GPIO5","IO断电","OUT"));
//                        serialMessageAdapter.addItem(new SerialMessage("INT","IO断电","OUT"));
//                       // serialMessageAdapter.addItem(new SerialMessage("RST","IO断电","OUT"));
//                        serialMessageListView.scrollToPosition(serialMessageAdapter.getItemCount()-1);
//                    }else{
//                        tcwManager.execSuCmd("echo 1 > sys/class/gpio_sw/PB15/data");
//                        tcwManager.execSuCmd("echo 1 > sys/class/gpio_sw/PB16/data");
//                        tcwManager.execSuCmd("echo 1 > sys/class/gpio_sw/PB17/data");
//                        tcwManager.execSuCmd("echo 1 > sys/class/gpio_sw/PH0/data");
//                     //   tcwManager.execSuCmd("echo 1 > sys/class/gpio_sw/PH1/data");
//                        serialMessageAdapter.addItem(new SerialMessage("GPIO3","IO通电","OUT"));
//                        serialMessageAdapter.addItem(new SerialMessage("GPIO4","IO通电","OUT"));
//                        serialMessageAdapter.addItem(new SerialMessage("GPIO5","IO通电","OUT"));
//
//                        serialMessageAdapter.addItem(new SerialMessage("INT","IO通电","OUT"));
//                      //  serialMessageAdapter.addItem(new SerialMessage("RST","IO通电","OUT"));
//                        serialMessageListView.scrollToPosition(serialMessageAdapter.getItemCount()-1);
//                    }
//                    handler.sendEmptyMessageDelayed(0,5000);
                    break;

                case 1:
                    String gpio1Data=readTxtFile("sys/class/gpio_sw/PB18/data");
                    String gpio2Data=readTxtFile("sys/class/gpio_sw/PB14/data");
                    String gpio3Data=readTxtFile("sys/class/gpio_sw/PB19/data");
                    if(gpio1Data!=null&&!gpio1Data.equals(ioTags[0])){
                        serialMessageAdapter.addItem(new SerialMessage("SCK","1".equals(gpio1Data)?"IO断开":"IO短接","IN"));
                    }
                    if(gpio2Data!=null&&!gpio2Data.equals(ioTags[1])){
                        serialMessageAdapter.addItem(new SerialMessage("GPIO2","1".equals(gpio2Data)?"IO断开":"IO短接","IN"));
                    }
                    if(gpio3Data!=null&&!gpio3Data.equals(ioTags[2])){
                        serialMessageAdapter.addItem(new SerialMessage("SDA","1".equals(gpio3Data)?"IO断开":"IO短接","IN"));
                    }

                    serialMessageListView.scrollToPosition(serialMessageAdapter.getItemCount()-1);
                    handler.sendEmptyMessageDelayed(1,1000);
                    ioTags[0]=gpio1Data;
                    ioTags[1]=gpio2Data;
                    ioTags[2]=gpio3Data;
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_usbserial_log);
        x.view().inject(this);
        SerialMessageReceiver serialMessageReceiver=new SerialMessageReceiver();
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction(Constants.ACTION_SETIAL_MSG);
        registerReceiver(serialMessageReceiver,intentFilter);
        serialMessageAdapter=new SerialMessageAdapter(this);
        serialMessageListView.setAdapter(serialMessageAdapter);
        serialMessageListView.setLayoutManager(new LinearLayoutManager(this));
        List<String> portList = new ArrayList<String>();
        for(int i=1;i<=9;i++){
            portList.add("USB"+i);
        }
        for(int i=1;i<=7;i++){
            portList.add("ttyS"+i);
        }
        ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, portList);
        portSpinner.setAdapter(adapter);
        portSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){

            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                cPort= (String) adapterView.getItemAtPosition(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }

        });
        tcwManager=TCWManager.getInstance(this);
    }


    public static String readTxtFile(String filePath){
        String lineTxt=null;
        try {
            String encoding="GBK";

            { //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(filePath),encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                lineTxt= bufferedReader.readLine();
                read.close();

            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return lineTxt;
    }

    public void sendHexMessage(View view){
        String message=messageSend.getText().toString();
        if(message.length()==0){
            Toast.makeText(USBSerialLogActivity.this,"不能发送空指令",Toast.LENGTH_SHORT).show();
            return ;
        }
        if(!message.matches("^[A-Fa-f0-9]+$")){
            Toast.makeText(USBSerialLogActivity.this,"字符格式必须是16进制字符",Toast.LENGTH_SHORT).show();
            return ;
        }
        USBSerialManager.getInstence().sendSerialMessageFromPort(cPort,cPort.contains("USB"),message);
        //messageSend.getEditableText().clear();
    }

    class SerialMessageReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String action=intent.getAction();
            if(Constants.ACTION_SETIAL_MSG.equals(action)){
                String serialMessageStr=intent.getStringExtra("serial_msg");
                if(serialMessageStr!=null){
                    SerialMessage serialMessage=JSON.parseObject(serialMessageStr, SerialMessage.class);
                    serialMessageAdapter.addItem(serialMessage);
                    serialMessageListView.scrollToPosition(serialMessageAdapter.getItemCount()-1);
                }
            }
        }
    }
}